<?php 

class Event_CategoryFilterPreSave extends Crud_Event_Handler
{
	protected $_type = 'preSave';
	
	public function run($row)
	{
		DB::getConnection()->rollBack();
		$id_category = $this->_getParam('category_id');
		$property = $this->_getParam('property', array());
		$rowProp = $this->select_filter($id_category, $property);
		$property = array_values($property);
		$rowProp = array_values($rowProp);
		$row = array_merge($property, $rowProp);
		$row = array_unique($row);

		if(count($rowProp)==0 && count($property)>0){
			foreach($property as $item)
			{
				$this->insert_filter($item, $id_category);
			}
		}else{
			if(count($row) > 0){
				$this->setters($row, $property, $rowProp, $id_category);
			}
		}
		header('location: /admin/crud/list/table/category2product_attribute');
		exit;
	}

	protected function setters($work_ids, $property, $rowProp, $id_category)
	{
		foreach($work_ids as $key => $value){
			if(in_array($value,$rowProp) && !in_array($value,$property)){
				$this->delete_filter($value, $id_category);
			}else if(in_array($value,$property) && !in_array($value,$rowProp)){
				$this->insert_filter($value, $id_category);
			}
		}
	}

	protected function select_filter($id_category, $property = array())
	{
		$db = DB::getConnection()->fetchAll("SELECT attribute_id FROM `category2product_attribute` WHERE category_id=".$id_category);
		$idsAttrib = array();
			foreach($db as $id){
					$idsAttrib[] = $id['attribute_id'];
			}
		return $idsAttrib;
	}

	protected function insert_filter($id_attr, $id_category)
	{
		DB::getConnection()->query("insert into `category2product_attribute` set `category_id`=".$id_category.", `attribute_id`=".$id_attr);
	}

	protected function delete_filter($id_attr, $id_category)
	{
		DB::getConnection()->query("DELETE FROM `category2product_attribute` WHERE `category_id`=".$id_category." AND `attribute_id`=".$id_attr);
	}
}
